import { app, $$ } from "../experience/utils/F7.js";
import { CONF } from "../configure/Assets.js"
import Db from "../experience/db/Db.js";
import Api from "../experience/api/Api.js";
import Utils from "../experience/utils/Utils.js";
import Algorithm from "../experience/utils/Algorithm.js";
import Drawer from "../experience/drawer/Drawer.js";
import Uploader from "../component/other/Uploader.js";
import Track from "../component/route/Track.js";
import Position from "../component/route/Position.js";
import Selector from "../component/other/Selector.js";
import Coordinate from "../component/other/Coordinate.js";
import Person from "../component/location/Person.js";
import Vehicle from "../component/location/Vehicle.js";
import Measure from "../component/other/Measure.js";
import Route from "../component/route/Route.js";

class Yukirin {
    constructor() {
        if (Yukirin.instance) {
            return Verdandi.instance;
        }
        Yukirin.instance = this;

        this.db = new Db();
        this.api = new Api();
        this.utils = new Utils();
        this.algo = new Algorithm();
        this.drawer = new Drawer();

        this.init().then(() => {
            this.header();

            new Uploader();

            console.log("Walküre Fly...");
        });
    }

    header() {
        const headerDiv = `
            <header id="header">
                <div class="row">
                    <div class="col-100 function">
                        <button class="button button-fill color-primary" id="upload-popup">更新图纸</button>
                    </div>
                </div>
            </header>
        `;
        $$("#app").prepend(headerDiv);
    }

    async update(meta_id) {
        app.dialog.preloader("正在获取矿图...");
        const data = await this.api.getVector(meta_id);
        if (data.code === 0) {
            // 初始化config信息
            this.drawer.init(data.data.meta, data.data.layers);

            // 将从网络上取下来的数据存入数据库
            this.db.init(data.data).then(() => {
                // 从本地提取数据
                this.drawer.location().then(() => {
                    app.dialog.close();
                });
            });
        }
    }

    // 全局初始化
    async init() {
        const code = await this.api.getCode();
        this.utils.setLocalStorage('code', code.data);

        const config = this.algo.getConfig();
        if (config === null) {
            const metas = await this.api.getMetas(CONF.MINE_CODE);
            if (metas.code === 0 && metas.data.length > 0) {
                await this.update(metas.data[0]);
            }
        } else {
            // 从本地获取数据
            await this.drawer.location();
        }
    }
}

new Yukirin();